package com.sansecy.app;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ImageServer {
    private static final int PORT = 12345;
    private ServerSocket serverSocket;
    private boolean running = false;
    private ImageReceiver imageReceiver;

    public ImageServer(ImageReceiver imageReceiver) {
        this.imageReceiver = imageReceiver;
    }

    private static final String TAG = "ImageServer";
    public void start() {
        running = true;
        new Thread(() -> {
            try {
                serverSocket = new ServerSocket(PORT);
                Log.d(TAG, "Server started on port " + PORT);
                Socket clientSocket = serverSocket.accept();
                Log.d(TAG, "start() called running " + running);
                try (InputStream inputStream = clientSocket.getInputStream()) {
                    byte[] buffer = new byte[10240];
                    int bytesRead;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                    Log.d(TAG, "run() called bytesRead :" + bytesRead);
                        for (int i = 0; i < buffer.length; i++) {
                            if (buffer[i] == '\n') { // 检测到特定字符
                                byte[] imageData = baos.toByteArray();
                                baos.reset(); // 重置流以开始存储新数据
                                SPExecutor.get().runOnUiThread(() -> imageReceiver.onImageReceived(imageData));
                            } else {
                                baos.write(buffer[i]);
                            }
                        }
                    }
                } catch (IOException e) {
                    Log.e(TAG, "start: ", e);
                }
            } catch (IOException e) {
                Log.e(TAG, "start: ", e);
            }
        }).start();
    }

    public void stop() {
        running = false;
        try {
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class ClientHandler implements Runnable {
        private Socket clientSocket;
        private static final String TAG = "ClientHandler";
        public ClientHandler(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        @Override
        public void run() {

        }
    }

    public interface ImageReceiver {
        void onImageReceived(byte[] imageData);
    }
}